package com.suray.wcs.web.system.controller;

import com.suray.basic.wcs.path.enums.NodeType;
import com.suray.commin.annotation.Log;
import com.suray.commin.core.controller.BaseController;
import com.suray.commin.core.page.TableDataInfo;
import com.suray.commin.core.controller.ResponseData;
import com.suray.commin.core.utils.StringUtils;
import com.suray.commin.enmus.BusinessType;
import com.suray.wcs.service.enums.PlcType;
import com.suray.wcs.service.init.SystemInit;
import com.suray.wcs.service.pojo.NodeInfo;
import com.suray.wcs.service.system.entity.NodeDB;
import com.suray.wcs.service.system.entity.PlcDB;
import com.suray.basic.wcs.plc.entity.PlcDeviceDB;
import com.suray.wcs.service.system.entity.ProgrammeDB;
import com.suray.wcs.service.system.service.IPlcDBService;
import com.suray.wcs.service.system.service.impl.NodeDBServiceImpl;
import com.suray.basic.wcs.plc.service.impl.PlcDeviceDBServiceImpl;
import com.suray.wcs.service.system.service.impl.ProgrammeServiceImpl;
import com.suray.wcs.service.websocket.NodeInfoPush;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * plc管理界面控制器
 *
 * @author zhanghr
 */
@RestController
@RequestMapping("/Plc")
public class PlcDBController extends BaseController {

    @Autowired
    private IPlcDBService plcDBService;
    @Autowired
    private PlcDeviceDBServiceImpl plcDeviceDBService;
    @Autowired
    private ProgrammeServiceImpl programmeService;
    @Autowired
    private NodeDBServiceImpl nodeDBService;

    /**
     * 查询Plc信息
     *
     * @return
     */
    @ApiOperation("查询Plc信息")
    @PreAuthorize("@ss.hasPermi('Plc:query')")
    @GetMapping(value = "/list")
    public TableDataInfo queryPlcInfo(PlcDB plcdb) {
        startPage();
        List<PlcDB> list = plcDBService.selectPlcList(plcdb);
        return getDataTable(list);
    }

    /**
     * 根据plc编号获取详细信息
     */
    @ApiOperation("根据plc编号获取详细信息")
    @GetMapping(value = "/{plcId}")
    public ResponseData getInfo(@PathVariable Long plcId) {
        return ResponseData.success(plcDBService.selectPlcById(plcId));
    }

    /**
     * 新增PLC
     *
     * @param plcDB
     * @return
     */
    @Log(title = "plc管理界面控制", method = "新增PLC", businessType = BusinessType.INSERT)
    @ApiOperation("新增PLC")
    @PostMapping(value = "/addPlc")
    @PreAuthorize("@ss.hasPermi('Plc:add')")
    public ResponseData addPlcInfo(@Validated @RequestBody PlcDB plcDB) {
        if (plcDBService.checkPlcNameUnique(plcDB)) {
            return ResponseData.error("新增PLC'" + plcDB.getPlcName() + "'失败，PLC名称已存在");
        }
        return toAjax(plcDBService.addPlc(plcDB));
    }


    /**
     * 修改是否启用
     *
     * @param plcDB
     * @return
     */
    @Log(title = "plc管理界面控制", method = "修改是否启用", businessType = BusinessType.UPDATE)
    @ApiOperation("修改是否启用")
    @PostMapping("/changeDisable")
    @PreAuthorize("@ss.hasPermi('Plc:edit')")
    public ResponseData changeDisable(@Validated @RequestBody PlcDB plcDB) {
        Integer plcType = plcDBService.getById(plcDB.getPlcId()).getPlcType();
        if (PlcType.PANASONIC.getValue().equals(plcType) || PlcType.AUTOMATIC_LIFTER.getValue().equals(plcType)
                || PlcType.SIEMENS.getValue().equals(plcType)
                || PlcType.TAMAGAWA.getValue().equals(plcType)) {
            List<ProgrammeDB> programmeDBS = programmeService.queryProgrammeConf(new ProgrammeDB());
            for (ProgrammeDB programmeDB : programmeDBS) {
                if (StringUtils.isEmpty(programmeDB.getProgramme())) {
                    continue;
                }
                String[] split = programmeDB.getProgramme().split("-");
                for (String deviceNo : split) {
                    PlcDeviceDB plcDeviceDB = plcDeviceDBService.getPlcDevById(Integer.valueOf(deviceNo));
                    if (plcDeviceDB != null && plcDB.getPlcId().equals(plcDeviceDB.getPlcId())) {
                        programmeDB.setStatus(plcDB.getStatus());
                        programmeService.updateProgrammeDB(programmeDB);
                        SystemInit.initProgrammeMap();
                    }
                }
            }
        }
        if (PlcType.parsePlcType(plcType).toString().contains("提升机")) {
            //同步plcDevice的禁用状态
            List<PlcDeviceDB> plcDeviceDBS = plcDeviceDBService.selectPlcDevByPlcId(plcDB.getPlcId());
            for (PlcDeviceDB plcDeviceDB : plcDeviceDBS) {
                if (!StringUtils.isEmpty(plcDeviceDB.getPlcLockLocation())) {
                    List<NodeDB> nodeListLift = nodeDBService.getNodeListLift(plcDeviceDB);
                    for (NodeDB nodeDB : nodeListLift) {
                        // 把提升机相应的位置禁用
                        nodeDB.setGridType(plcDB.getStatus().equals("1") ? NodeType.B : NodeType.L);
                        nodeDBService.updateById(nodeDB);
                        NodeInfo nodeInfo = new NodeInfo();
                        BeanUtils.copyProperties(nodeDB, nodeInfo);
                        NodeInfoPush.push(nodeInfo);
                    }
                }
                plcDeviceDBService.updatePlcDeviceByPlcId(plcDeviceDB, plcDB.getStatus());
            }
        }
        return toAjax(plcDBService.updateDisableById(plcDB));
    }

    /**
     * 删除PLC
     *
     * @param plcIds
     * @return
     */
    @Log(title = "plc管理界面控制", method = "删除Plc", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/delete/{plcIds}")
    @ApiOperation(value = "删除Plc")
    @PreAuthorize("@ss.hasPermi('Plc:remove')")
    public ResponseData deletePlcInfo(@PathVariable Long[] plcIds) {
        for (Long plcId : plcIds) {
            if (plcDBService.hasChildByPlcId(plcId)) {
                return ResponseData.error(plcId + "存在子设备,不允许删除");
            }
        }
        return toAjax(plcDBService.removeByIds(Arrays.asList(plcIds)));
    }

    @PreAuthorize("@ss.hasPermi('Plc:edit')")
    @Log(title = "plc管理界面控制", method = "修改Plc", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/changePlc")
    @ApiOperation(value = "修改Plc")
    @ResponseBody
    public ResponseData changePlcInfo(@Validated @RequestBody PlcDB plcdb) {
        if (plcDBService.checkPlcNameUnique(plcdb)) {
            return ResponseData.error("plc名称已经存在");
        }
        if (plcDBService.updatePlc(plcdb)) {
            return ResponseData.success("修改成功,重启服务生效");
        } else {
            return ResponseData.error("修改PLC失败");
        }
    }

    /**
     * 查询提升机Plc信息
     *
     * @return
     */
    @ApiOperation("查询提升机Plc信息")
    @GetMapping(value = "/lifterList")
    public ResponseData getLifters() {
        return ResponseData.success(plcDBService.getLifterInfosByType());
    }
}
